package com.steve.combat.algorithm.douyin;

/**
 * @Author: STEVE
 * @Description: 动态规划解决兔子繁殖问题
 * @since: 2025-04-18
 */
public class RabbitDP {

    /**
     * 动态规划解法（使用数组）
     * 时间复杂度（O(n)）
     * 空间复杂度（O(n)）
     */
    public static int fibonacciDP(int n) {
        if (n == 1 || n == 2) {
            return 1;
        }
        int[] dp = new int[n + 1];
        dp[1] = 1;
        dp[2] = 1;
        for (int i = 3; i <= n; i++) {
            dp[i] = dp[i - 1] + dp[i - 2];
        }
        return dp[n];
    }

    /**
     * 空间优化的动态规划解法
     * 时间复杂度：O(n)
     * 空间复杂度：O(1)
     */
    public static int fibonacciDPOptimized(int n) {
        if (n == 1 || n == 2) {
            return 1;
        }
        int prev = 1;
        int curr = 1;
        for (int i = 3; i <= n; i++) {
            int sum = prev + curr;
            prev = curr;
            curr = sum;
        }
        return curr;
    }

    public static void main(String[] args) {
        int month = 10;
        System.out.println("动态规划解法 - 第" + month + "个月的兔子对数: " + fibonacciDPOptimized(month));
    }

}
